package com.gewu.pm.ui.activity.delivery;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.androidkun.xtablayout.XTabLayout;
import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.app.AppFragment;
import com.gewu.pm.ui.activity.filter.FilterMultipleActivity;
import com.gewu.pm.ui.fragment.delivery.DeliveryOrderFragment;
import com.gewu.pm.ui.popup.SelectTimePopup;
import com.hjq.base.FragmentPagerAdapter;

import java.util.Arrays;
import java.util.List;

/**
 * 配送管理（订单）
 */
public final class DeliveryManagementOrderActivity extends AppActivity {

    private TextView mDateFilterView;
    private EditText mSearchEdit;
    private XTabLayout mTabLayout;
    private ViewPager mViewPager;

    private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter;
    private DeliveryOrderFragment mAllFragment;                // 全部
    private DeliveryOrderFragment mPendingDeliveryFragment;    // 待发货
    private DeliveryOrderFragment mPendingReceiptFragment;     // 待签收
    private DeliveryOrderFragment mReceivedFragment;           // 已签收
    private DeliveryOrderFragment mCancelledFragment;          // 已取消

    private String mCurrentDateFilter = "今日";  // 当前日期筛选

    public static void start(Context context) {
        Intent intent = new Intent(context, DeliveryManagementOrderActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.delivery_management_order_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mDateFilterView = findViewById(R.id.tv_date_filter);
        mSearchEdit = findViewById(R.id.et_search);
        mTabLayout = findViewById(R.id.tab_layout);
        mViewPager = findViewById(R.id.vp_content);

        // 创建 Fragment（每个Tab独立的Fragment实例）
        mAllFragment = DeliveryOrderFragment.newInstance(0);              // 全部（type=0表示全部）
        mPendingDeliveryFragment = DeliveryOrderFragment.newInstance(1);  // 待发货
        mPendingReceiptFragment = DeliveryOrderFragment.newInstance(2);   // 待签收
        mReceivedFragment = DeliveryOrderFragment.newInstance(3);         // 已签收
        mCancelledFragment = DeliveryOrderFragment.newInstance(4);        // 已取消

        // 设置 ViewPager
        mPagerAdapter = new FragmentPagerAdapter<>(this);
        mPagerAdapter.addFragment(mAllFragment, "全部");
        mPagerAdapter.addFragment(mPendingDeliveryFragment, "待发货");
        mPagerAdapter.addFragment(mPendingReceiptFragment, "待签收");
        mPagerAdapter.addFragment(mReceivedFragment, "已签收");
        mPagerAdapter.addFragment(mCancelledFragment, "已取消");
        mViewPager.setAdapter(mPagerAdapter);

        // 关联 XTabLayout 和 ViewPager
        mTabLayout.setupWithViewPager(mViewPager);

        // 设置搜索监听
        mSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString().trim();
                performSearch(keyword);
            }
        });

        // 设置点击事件
        setOnClickListener(mDateFilterView);
    }

    @Override
    protected void initData() {
    }

    /**
     * 执行搜索
     */
    private void performSearch(String keyword) {
        // 通知当前显示的 Fragment 执行搜索
        int currentIndex = mViewPager.getCurrentItem();
        
        if (currentIndex == 0) {
            mAllFragment.search(keyword);
        } else if (currentIndex == 1) {
            mPendingDeliveryFragment.search(keyword);
        } else if (currentIndex == 2) {
            mPendingReceiptFragment.search(keyword);
        } else if (currentIndex == 3) {
            mReceivedFragment.search(keyword);
        } else if (currentIndex == 4) {
            mCancelledFragment.search(keyword);
        }
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.tv_date_filter) {
            // 日期筛选
            showDateFilterPopup();
        }
    }

    @Override
    public void onRightClick(View view) {
        super.onRightClick(view);
        FilterMultipleActivity.start(getActivity());
    }

    /**
     * 显示日期筛选弹窗
     */
    private void showDateFilterPopup() {
        List<String> dateList = Arrays.asList("今日", "7天", "一个月");
        SelectTimePopup.Builder builder = new SelectTimePopup.Builder(this)
                .setList(dateList)
                .setSelectedItem(mCurrentDateFilter)
                .setListener((popupWindow, category) -> {
                    mCurrentDateFilter = category;
                    mDateFilterView.setText(category);
                    
                    // 通知所有Fragment刷新数据
                    refreshAllFragments();
                });
        
        builder.showAsDropDown(mDateFilterView);
    }

    /**
     * 刷新所有Fragment数据
     */
    private void refreshAllFragments() {
        mAllFragment.setDateFilter(mCurrentDateFilter);
        mPendingDeliveryFragment.setDateFilter(mCurrentDateFilter);
        mPendingReceiptFragment.setDateFilter(mCurrentDateFilter);
        mReceivedFragment.setDateFilter(mCurrentDateFilter);
        mCancelledFragment.setDateFilter(mCurrentDateFilter);
    }
}
